<template>
    <div class="department">
  
        <div class="department__header">
          <div
            class="department__header--list"
          >
            <div
              v-for="(item, index) in numList"
              :key="index"
              class="department__header--item"
            >
              <svg-icon :icon-class="item.icon" style="width: 100%; height: 128px;" />
              <div
                class="department__header--item-data"
                :style="{color: item.color}"
              >
                <span style="margin-bottom: 20px">{{ item.label }}</span>
                <span>{{ item.value ?? '--' }}</span>
              </div>
            </div>
          </div>
        </div>
      <el-divider />
  
        <div class="department__body">
          <div class="department__body-tree-menu">
            <el-tree
              :data="departmentList"
              :props="elTreeOptions.defaultProps"
              accordion
              :expand-on-click-node="false"
              highlight-current
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              @node-click="handleNodeClick"
            >
              <template v-slot="{ node, data }">
                <div class="custom-tree-node">
                  <span>{{ data.name }}</span>
                  <el-dropdown @command="handleDropdownClick($event, data)">
                    <div
                      v-show="data.id === elTreeOptions.currentNode"
                      class="custom-tree-node-button"
                    >
                      <i class="el-icon-more" />
                    </div>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="edit">编辑</el-dropdown-item>
                        <el-dropdown-item command="remove">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-tree>
            <div class="department__body-tree-menu-add-button">
              <el-button type="text" icon="el-icon-plus" @click="handleOpenDialog('create')">
                新建部门
              </el-button>
            </div>
          </div>
          <div class="demo">
            <el-divider direction="vertical" />
          </div>
          <div class="department__body-content">
            <div class="department__body-content-header">
              <span class="department__name">{{ currentDepartment.name }}</span>
              <span style="color: #bbb; font-size: 14px; margin-left: 10px">
                <svg-icon icon-class="user-manger" />
                {{ currentDepartment.count }}
              </span>
            </div>
    
            <div class="department__body-content-table">
              <el-table
                v-loading="loading"
                :data="currentDepartEmployee"
                :header-cell-style="{background: '#F5F7FA'}"
                height="550px"
              >
                <el-table-column align="center" prop="username" label="姓名" />
                <el-table-column align="center" label="性别">
                  <template v-slot="{ row }">
                    <span>
                      {{ row.gender === 1 ? '男' : row.gender === 0 ? '女' : '不详' }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="phone" label="手机号" />
                <el-table-column align="center" label="操作">
                  <template v-slot="{ row }">
                    <el-button type="text" @click="handleJumpTo(row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
  
      <el-dialog
        :visible.sync="dialogOptions.show"
        :show-close="false"
        width="300px"
        :close-on-click-modal="false"
      >
        <template #title>
          <div class="dialog-header">
            <span>{{ dialogOptions.title }}</span>
            <i class="icon el-icon-close" @click="dialogOptions.show = false" />
          </div>
        </template>
        <div class="dialog-body">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="formData"
            label-width="auto"
            label-position="left"
          >
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入部门名称" />
            </el-form-item>
            <el-form-item label="部门领导">
              <el-select
                v-model="formData.leader_id"
                filterable
                placeholder="请选择部门领导"
                :filter-method="onSearchEvent"
                :loading="searchLoading"
              >
                <el-option
                  v-for="(item, index) in selectOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="父级部门">
              <el-cascader
                v-model="formData.parent_id"
                clearable
                :options="departmentList"
                placeholder="请选择父级部门"
                :props="{ value: 'id', label: 'name', checkStrictly: true }"
              />
            </el-form-item>
            <el-form-item label="是否为父级部门">
              <el-radio-group v-model="formData.is_directory">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="部门描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                placeholder="请输入部门描述"
                :maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogOptions.show = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { mapGetters } from 'vuex'
  import { addDept, editDept, delDept, numDept } from '@/api/dept'
  import { getDept, getDeptpeople } from '@/api/basic'
  import { getAllUser } from '@/api/personnel'
  import { deepClone } from '@/utils'
  export default {
    name: 'Department',
    data() {
      return {
        departNum: {},
        departmentList: [],
        elTreeOptions: {
          currentNode: null,
          defaultProps: {
            label: 'name',
            chidren: 'chidren'
          }
        },
        loading: false,
        currentDepartment: {
          name: '',
          count: null
        },
        currentDepartEmployee: [],
        dialogOptions: {
          show: false,
          title: '新建部门'
        },
        formData: {
          name: '',
          leader_id: null,
          parent_id: null,
          is_directory: 0,
          description: ''
        },
        rules: {
          name: [
            {
              required: true,
              message: '请输入部门名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 10,
              message: '长度在 1 到 10 个字符',
              trigger: 'blur'
            }
          ]
        },
        selectOptions: [],
        params: {
          username: '',
          paginate: 50
        },
        searchLoading: false,
        defaultExpandedKeys: []
      }
    },
    computed: {
      ...mapGetters(['defaultCompany']),
      numList() {
        const { delNum, departmentNum, oneNum } = this.departNum
        return [
          {
            label: '部门数量',
            value: departmentNum,
            icon: 'department-count',
            color: '#DA7D5D'
          },
          {
            label: '父级部门',
            value: oneNum,
            icon: 'p-department-count',
            color: '#18BE86'
          },
          {
            label: '回收站',
            value: delNum,
            icon: 'recycle-bin',
            color: '#286CBD'
          }
        ]
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        Promise.allSettled([
          this.getDepartNum(),
          this.getDepartmentsList(),
          this.getDepartmentPeople(),
          this.getAllUserList()
        ])
        this.currentDepartment.name = this.defaultCompany.name
      },
      async getDepartNum() {
        try {
          const res = await numDept()
          this.departNum = res.data
        } catch (error) {
          console.log('error--------->', error)
        }
      },
      async getDepartmentsList() {
        try {
          const res = await getDept()
          this.departmentList = res.data
        } catch (error) {
          this.$message.error('获取部门数据失败')
        }
      },
      async getDepartmentPeople(data) {
        this.loading = true
        try {
          const date = {
            department_id: data?.id || null
          }
          const res = await getDeptpeople(date)
          this.currentDepartEmployee = res.data
          this.currentDepartment.count = res.data.length
        } catch (error) {
          this.$message.error('部门成员获取失败')
        } finally {
          this.loading = false
        }
      },
  
      async getAllUserList() {
        try {
          const res = await getAllUser(this.params)
          this.selectOptions =
            res.data.map(item => ({ label: item.username, value: item.id }))
        } catch (error) {
          console.log('error--------->', error)
        }
      },
      onSearchEvent(e) {
        delete this.params.user_id
        this.searchLoading = true
        this.params.username = e
        this.getAllUserList()
        this.searchLoading = false
      },
  
      handleNodeClick(data, node) {
        this.elTreeOptions.currentNode = data.id
        this.currentDepartment.name = data.name
  
        this.getDepartmentPeople(data)
      },
  
      async handleOpenDialog(type, data) {
        this.reset()
        if (type === 'create') {
          this.dialogOptions.title = '新建部门'
        } else {
          this.params.user_id = data.leader_id
          const a = deepClone(this.selectOptions)
          await this.getAllUserList()
          this.selectOptions = Array.from(new Set([...this.selectOptions, ...a]
            .map(JSON.stringify))).map(JSON.parse)
          this.dataEcho(data)
          this.dialogOptions.title = '修改部门'
        }
        this.dialogOptions.show = true
        this.$nextTick(() => {
          this.$refs.formRef.clearValidate()
        })
      },
  
      dataEcho(data) {
        const { id, leader_id, description, is_directory, name, parent_id } = data
        this.formData.id = id
        this.formData.leader_id = leader_id
        this.formData.description = description
        this.formData.is_directory = is_directory
        this.formData.parent_id = parent_id
        this.formData.name = name
      },
  
      handleSubmit() {
        this.$refs.formRef.validate(valid => {
          if (valid) {
            if (!this.formData.id) {
              this.createDepartmentApi(this.formatParams(this.formData))
            } else {
              this.editDepartmentApi(this.formatParams(this.formData))
            }
          }
        })
      },
  
      handleDropdownClick(e, data) {
        if (e === 'edit') {
          this.handleOpenDialog('edit', data)
        } else {
          this.$confirm(
            '是否删除该部门',
            { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
          ).then(() => {
            const node = this.findParents(data.id, this.departmentList)
            if (node.parent_id) this.defaultExpandedKeys.push(node.parent_id)
            this.removeDepartmentApi({ id: data.id })
          })
        }
      },
  
      async removeDepartmentApi(data) {
        try {
          const res = await delDept(data)
          if (res.code === 200 || res.code === 201) {
            this.$message.success('删除成功')
            this.refresh()
            this.currentDepartment.name = this.defaultCompany.name
            await this.getDepartmentPeople()
          } else {
            this.$message.error(res.message)
          }
        } catch (error) {
          this.$message.error('部门删除失败')
        }
      },
      formatParams(params) {
        const { parent_id, ...restParams } = params
        const data = {
          ...restParams,
          parent_id:
            Array.isArray(parent_id) ? parent_id.slice(-1)[0]
              : parent_id !== null ? parent_id : null
        }
        Object.keys(data).forEach(item => {
          if (item === null) delete data[item]
        })
        return data
      },
  
      async createDepartmentApi(params) {
        try {
          const res = await addDept(params)
          if (res.code >= 200 || res.code <= 299) {
            this.$message.success('部门创建成功')
            if (params.parent_id) this.defaultExpandedKeys.push(params.parent_id)
            this.refresh()
          }
        } catch (error) {
          this.$message(error.responseEnd.data.message || '部门创建失败')
        }
      },
  
      findParents(id, treeList) {
        for (var i = 0; i < treeList.length; i++) {
          const item = treeList[i]
          if (item.id === id) {
            return item
          }
          if (item.children && item.children.length > 0) {
            const child = this.findParents(id, item.children)
            if (child) return child
          }
        }
        return null
      },
  
      async editDepartmentApi(data) {
        try {
          const res = await editDept(data)
          if (res.code >= 200 || res.code <= 299) {
            this.$message.success('部门修改成功')
            this.refresh()
          }
        } catch (error) {
          this.$message(error.responseEnd.data.message || '部门修改失败')
        }
      },
  
      refresh() {
        this.getDepartNum()
        this.getDepartmentsList()
        // this.getDepartmentPeople()
        this.dialogOptions.show = false
      },
  
      reset() {
        this.formData = this.$options.data().formData
      },
      handleJumpTo(row) {
        this.$router.push({
          path: `/personnel-files/show/${row.id}`,
          query: { tag_title: row.username + '-查看', show: true }
        })
      }
    }
  }
  </script>
  
  <style scoped lang='scss'>
  .department {
    padding: 20px;
    background-color: #fff;
    &__header {
      padding: 20px;
      &--list {
        display: flex;
        //justify-content: space-around;
      }
      &--item {
        position: relative;
        &:nth-child(2n) {
          margin: 0 30px;
        }
        &-data {
          font-size: 18px;
          display: flex;
          flex-direction: column;
          position: absolute;
          left: 30px;
          top: 30px;
        }
      }
    }
  
    &__body {
      display: flex;
      padding: 20px;
      &-tree-menu {
        padding: 0 5px 0 0;
        width: 25%;
        &-add-button {
          margin-top: 20px;
          display: flex;
          justify-content: center;
        }
        .custom-tree-node {
          cursor: default;
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          padding-right: 8px;
          //display: flex;
          &-button {
            height: 20px;
            padding: 0 5px;
            display: flex;
            align-items: center;
            transition: all .3s;
            &:hover {
              background: #E8E8E8;
            }
          }
        }
      }
      &-content {
        flex: 1;
        padding: 0 20px;
        &-header {
          margin-bottom: 10px;
          .department__name {
            font-weight: bold;
          }
        }
      }
    }
    .dialog-header {
      font-size: 24px;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #DCDFE6;
      padding: 20px;
      .icon {
        color: #8E8E8E;
      }
    }
    .dialog-footer {
      padding: 20px;
      border-top: 1px solid #DCDFE6;
    }
  }
  :deep(.el-dialog__header) {
    padding: 0;
  }
  :deep(.el-dialog__footer) {
    padding: 0;
  }
  .demo .el-divider--vertical{
    display:inline-block;
    width:1px;
    height:100%;
    margin:0 8px;
    vertical-align:middle;
    position:relative;
  }
  </style>
  